package com.southwind.springboottest.controller;

import com.southwind.springboottest.entity.Country;
import com.southwind.springboottest.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/country")
public class CountryController {
    @Autowired
    private CountryRepository countryRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Country> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageRequest request = PageRequest.of(page-1,size);
        return countryRepository.findAll(request);
    }

    @GetMapping("/findAll")
    public List<Country> findAll(){
        return countryRepository.findAll();
    }

    @PostMapping("/save")
    public String save(@RequestBody Country country){
        Country result = countryRepository.save(country);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public Country findById(@PathVariable("id") Integer id){
        return countryRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Country country){
        Country result = countryRepository.save(country);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        countryRepository.deleteById(id);
    }
}
